package com.tech.zhidengxian.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tech.zhidengxian.mapper.MessageMapper;
import com.tech.zhidengxian.model.dataobject.GoodsDO;
import com.tech.zhidengxian.model.dataobject.MessageDO;
import com.tech.zhidengxian.model.dto.ChatDTO;
import com.tech.zhidengxian.model.dto.GoodsDTO;
import com.tech.zhidengxian.model.dto.MessageDTO;
import com.tech.zhidengxian.model.dto.page.MyPage;
import com.tech.zhidengxian.model.dto.request.MessageRequest;
import com.tech.zhidengxian.service.api.ChatService;
import com.tech.zhidengxian.service.api.MessageService;
import com.tech.zhidengxian.util.JacksonUtils;
import com.tech.zhidengxian.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Resource
    private MessageMapper messageMapper;

    @Resource
    private ChatService chatService;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertMessage(MessageDTO messageDTO) {
        int insert = 0;
        try {
            messageDTO.setCreateTime(TimeUtil.currentDate());
            messageDTO.setUpdateTime(TimeUtil.currentDate());
            messageDTO.setIsDeleted(false);
            MessageDO messageDO = JacksonUtils.convert(messageDTO,MessageDO.class);
            insert = messageMapper.insertMessage(messageDO);
            if (insert>0){
                messageDTO.setId(messageDO.getId());
                ChatDTO chatDTO = new ChatDTO();
                chatDTO.setId(messageDO.getCid());
                chatDTO.setUpdateTime(messageDTO.getCreateTime());
                chatDTO.setLastMessage(messageDTO);
                insert = chatService.refreshLastMsg4Chat(chatDTO);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            throw e;
        }
        return insert;
    }

    @Override
    public MyPage<MessageDTO> pageQueryMessage(MessageRequest messageRequest) {
        IPage<MessageDO> messageDOIPage = messageMapper.pageQueryMessage(messageRequest);
        List<MessageDO> records = messageDOIPage.getRecords();
        List<MessageDTO> messageDTOList = JacksonUtils.convertList(records, MessageDTO.class);
        return MyPage.of(messageDTOList,messageRequest.getCurrentPage(),messageRequest.getPageSize(),messageDOIPage.getTotal());
    }
}
